// 全局变量
let eventsData = [];
let currentEditIndex = -1;

// DOM元素
const startDateInput = document.getElementById('startDate');
const filenameInput = document.getElementById('filename');
const updateBtn = document.getElementById('updateBtn');
const downloadBtn = document.getElementById('downloadBtn');
const eventsList = document.getElementById('eventsList');
const totalEventsSpan = document.getElementById('totalEvents');
const totalWeeksSpan = document.getElementById('totalWeeks');
const statusDiv = document.getElementById('status');
const editModal = document.getElementById('editModal');
const editForm = document.getElementById('editForm');
const editTitle = document.getElementById('editTitle');
const editLocation = document.getElementById('editLocation');
const editDescription = document.getElementById('editDescription');
const cancelEditBtn = document.getElementById('cancelEdit');

// 显示状态消息
function showStatus(message, type = 'info') {
    statusDiv.textContent = message;
    statusDiv.className = `status ${type}`;
    statusDiv.style.display = 'block';
    
    setTimeout(() => {
        statusDiv.style.display = 'none';
    }, 3000);
}

// 格式化日期
function formatDate(date) {
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        weekday: 'long'
    });
}

// 格式化时间
function formatTime(date) {
    return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 生成ICS内容
function generateICSContent(events) {
    const lines = [
        "BEGIN:VCALENDAR",
        "VERSION:2.0",
        "PRODID:-//SMU Timetable Export//CN",
        "CALSCALE:GREGORIAN"
    ];
    
    function pad(n) { return (n < 10 ? '0' : '') + n; }
    
    function toICSDate(d) {
        const y = d.getFullYear();
        const m = pad(d.getMonth() + 1);
        const day = pad(d.getDate());
        const hh = pad(d.getHours());
        const mm = pad(d.getMinutes());
        const ss = pad(d.getSeconds());
        return `${y}${m}${day}T${hh}${mm}${ss}`;
    }
    
    function esc(s) {
        return String(s || '').replace(/([,;])/g, '\\$1').replace(/\n/g, '\\n');
    }
    
    events.forEach(event => {
        lines.push("BEGIN:VEVENT");
        lines.push("SUMMARY:" + esc(event.title));
        if (event.description) lines.push("DESCRIPTION:" + esc(event.description));
        if (event.location) lines.push("LOCATION:" + esc(event.location));
        lines.push("DTSTART:" + toICSDate(event.start));
        lines.push("DTEND:" + toICSDate(event.end));
        lines.push("UID:" + (Date.now() + '-' + Math.random()).replace(/\D/g, ''));
        lines.push("END:VEVENT");
    });
    
    lines.push("END:VCALENDAR");
    return lines.join("\r\n");
}

// 下载ICS文件
function downloadICS() {
    if (eventsData.length === 0) {
        showStatus('没有课程数据可下载', 'error');
        return;
    }
    
    try {
        const icsContent = generateICSContent(eventsData);
        const filename = filenameInput.value.trim() || 'timetable';
        const blob = new Blob([icsContent], { type: "text/calendar" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = filename.endsWith('.ics') ? filename : filename + '.ics';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        showStatus('ICS文件下载成功！', 'success');
    } catch (error) {
        console.error('下载失败:', error);
        showStatus('下载失败，请重试', 'error');
    }
}

// 渲染事件列表
function renderEventsList() {
    if (eventsData.length === 0) {
        eventsList.innerHTML = `
            <div class="empty-state">
                <div class="icon">📚</div>
                <p>暂无课程数据，请先更新预览</p>
            </div>
        `;
        downloadBtn.style.display = 'none';
        return;
    }
    
    // 更新统计信息
    const totalWeeks = new Set(eventsData.map(e => e.week)).size;
    totalEventsSpan.textContent = eventsData.length;
    totalWeeksSpan.textContent = totalWeeks;
    
    // 渲染事件列表
    eventsList.innerHTML = eventsData.map((event, index) => `
        <div class="event-item">
            <div class="event-header">
                <div class="event-title">${event.title}</div>
                <div class="event-time">${formatTime(event.start)} - ${formatTime(event.end)}</div>
            </div>
            <div class="event-details">
                <div class="event-detail"><strong>日期：</strong>${formatDate(event.start)}</div>
                <div class="event-detail"><strong>地点：</strong>${event.location || '未设置'}</div>
                <div class="event-detail"><strong>第${event.week}周</strong></div>
                <div class="event-detail"><strong>星期${event.weekday}</strong></div>
            </div>
            ${event.description ? `<div class="event-detail"><strong>描述：</strong>${event.description}</div>` : ''}
            <div class="event-actions">
                <button class="btn btn-edit btn-small" onclick="editEvent(${index})">编辑</button>
                <button class="btn btn-delete btn-small" onclick="deleteEvent(${index})">删除</button>
            </div>
        </div>
    `).join('');
    
    downloadBtn.style.display = 'inline-block';
}

// 编辑事件
function editEvent(index) {
    const event = eventsData[index];
    currentEditIndex = index;
    
    editTitle.value = event.title;
    editLocation.value = event.location || '';
    editDescription.value = event.description || '';
    
    editModal.style.display = 'block';
}

// 删除事件
function deleteEvent(index) {
    if (confirm('确定要删除这门课程吗？')) {
        eventsData.splice(index, 1);
        renderEventsList();
        showStatus('课程已删除', 'success');
    }
}

// 保存编辑
function saveEdit(event) {
    event.preventDefault();
    
    if (currentEditIndex === -1) return;
    
    const editedEvent = eventsData[currentEditIndex];
    editedEvent.title = editTitle.value.trim();
    editedEvent.location = editLocation.value.trim();
    editedEvent.description = editDescription.value.trim();
    
    renderEventsList();
    closeModal();
    showStatus('课程已更新', 'success');
}

// 关闭模态框
function closeModal() {
    editModal.style.display = 'none';
    currentEditIndex = -1;
    editForm.reset();
}

// 更新预览
async function updatePreview() {
    const startDate = startDateInput.value;
    
    if (!startDate) {
        showStatus('请选择起始日期', 'error');
        return;
    }
    
    // 验证日期是否为周一
    const date = new Date(startDate);
    const dayOfWeek = date.getDay();
    if (dayOfWeek !== 1) {
        showStatus('起始日期必须是周一', 'error');
        return;
    }
    
    try {
        showStatus('正在更新预览...', 'info');
        
        // 保存设置
        await chrome.storage.sync.set({
            semesterStartDate: startDate
        });
        
        // 通过background script重新获取数据
        chrome.runtime.sendMessage({
            action: 'refreshPreview',
            startDate: startDate
        });
        
        showStatus('请返回课表页面，然后重新点击插件图标获取最新数据', 'info');
        
    } catch (error) {
        console.error('更新预览失败:', error);
        showStatus('更新失败：' + error.message, 'error');
    }
}


// 加载保存的设置
async function loadSettings() {
    try {
        const result = await chrome.storage.sync.get(['semesterStartDate', 'isFirstTime']);
        if (result.semesterStartDate) {
            startDateInput.value = result.semesterStartDate;
        }
        
        // 检查是否首次使用
        if (result.isFirstTime !== false) {
            showStatus('欢迎使用！请先设置学期起始日期，然后点击"更新预览"', 'info');
            await chrome.storage.sync.set({ isFirstTime: false });
        }
    } catch (error) {
        console.error('加载设置失败:', error);
    }
}

// 事件监听器
updateBtn.addEventListener('click', updatePreview);
downloadBtn.addEventListener('click', downloadICS);
editForm.addEventListener('submit', saveEdit);
cancelEditBtn.addEventListener('click', closeModal);

// 模态框关闭事件
document.querySelector('.close').addEventListener('click', closeModal);
window.addEventListener('click', (event) => {
    if (event.target === editModal) {
        closeModal();
    }
});

// 处理来自background script的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'loadData') {
    loadPreviewData(message.data);
  }
});

// 加载预览数据
function loadPreviewData(data) {
  console.log('加载预览数据:', data); // 调试日志
  
  if (data && data.events && data.events.length > 0) {
    // 将ISO字符串转换回Date对象
    eventsData = data.events.map(event => ({
      ...event,
      start: new Date(event.start),
      end: new Date(event.end)
    }));
    
    if (data.startDate) {
      startDateInput.value = data.startDate;
    }
    if (data.filename) {
      filenameInput.value = data.filename;
    }
    renderEventsList();
    showStatus(`成功加载 ${eventsData.length} 门课程`, 'success');
  } else {
    console.log('没有有效的课程数据:', data);
    showStatus('没有找到课程数据', 'error');
  }
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', async () => {
  await loadSettings();
  
  // 尝试从storage加载预览数据
  try {
    const result = await chrome.storage.local.get(['previewData']);
    if (result.previewData) {
      loadPreviewData(result.previewData);
      // 清除临时数据
      chrome.storage.local.remove(['previewData']);
    }
  } catch (error) {
    console.error('加载预览数据失败:', error);
  }
});
